﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using FlowBasisSampleSite.Models;
using FlowBasis.Web.Security;
using FlowBasis.Data;
using FlowBasisSampleSite.Domain.Entities;
using FlowBasis.Security.Passwords;
using FlowBasisSampleSite.Lib.Security;

namespace FlowBasisSampleSite.Controllers
{
    public class AccountController : Controller
    {
        private Func<IDataService> dataServiceFactory;        
        private Func<IFormsAuthenticationService> formsAuthenticationServiceFactory;
        private Func<IHashedPasswordValidationService> passwordValidationServiceFactory;

        public AccountController(
            Func<IDataService> dataServiceFactory,            
            Func<IFormsAuthenticationService> formsAuthenticationServiceFactory,
            Func<IHashedPasswordValidationService> passwordValidationServiceFactory)
        {
            this.dataServiceFactory = dataServiceFactory;            
            this.formsAuthenticationServiceFactory = formsAuthenticationServiceFactory;
            this.passwordValidationServiceFactory = passwordValidationServiceFactory;
        }


        public ActionResult LogOn()
        {
            return View();
        }
     
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var dataService = this.dataServiceFactory();

                var userAccount = dataService.GetAll<UserAccount>().SingleOrDefault(ua => ua.PrimaryEmail == model.UserName);
                if (userAccount != null && !userAccount.IsDeleted)
                {
                    if (userAccount.PasswordHash != null)
                    {
                        var passwordValidationService = this.passwordValidationServiceFactory();

                        if (passwordValidationService.ValidatePassword(model.Password, userAccount.PasswordSalt, userAccount.PasswordHash))
                        {
                            // We use the user account token for the forms user name.
                            var formsAuthenticationService = this.formsAuthenticationServiceFactory();
                            formsAuthenticationService.SignIn(userAccount.UserToken, model.RememberMe);

                            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                            {
                                return Redirect(returnUrl);
                            }
                            else
                            {
                                return RedirectToAction("Index", "Home");
                            }
                        }
                    }
                }                                                             
            }

            // If we get this far, something failed, so redisplay login form.
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

      
        public ActionResult LogOff()
        {
            var formsAuthenticationService = this.formsAuthenticationServiceFactory();
            formsAuthenticationService.SignOut();            

            return RedirectToAction("Index", "Home");
        }


        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ForgotPassword(ForgotPasswordModel model)
        {            
            var passwordResetService = FlowBasis.Services.ServiceResolver.Instance.Get<PasswordResetService>();
            passwordResetService.ResetPasswordForEmailAddress(model.Email);        

            // TODO: pass indicator that password reset was requested.
            return RedirectToAction("LogOn");
        }
    }
}
